﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.WebSocket
{
    public class EchoWebSocketMiddleware : WebsocketMiddlewareBase
    {

        private readonly RequestDelegate _next;


        public EchoWebSocketMiddleware(ILogger<EchoWebSocketMiddleware> logger, RequestDelegate next)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context);
                return;
            }

            var mySocket = await ConnectClient(context);

            await Run(mySocket, async (socket, response) =>
             {
                 await SendStringAsync(socket.CurrentSocket, response, socket.SocketCancellationToken);
             });
        }


    }
}
